<template>
  <view class="page-container">
    <!-- 顶部导航栏 -->
    <uni-nav-bar
      :border="false"
      title="积分明细"
      fixed
      left-icon="back"
      @clickLeft="goBack"
    />

    <view class="content">
      <!-- 顶部积分卡片 -->
      <view class="points-card">
        <view class="points-row">
          <view class="points-item">
            <view class="points-label flex items-center"
              >补贴积分
              <uni-icons
                type="info"
                size="16"
                color="#999"
                @click.stop="showPointsInfo('subsidy')"
              ></uni-icons
            ></view>
            <text class="points-value">{{ pointsData.subsidy }}</text>
          </view>
          <view class="points-item">
            <view class="points-label flex items-center"
              >会员积分
              <uni-icons
                type="info"
                color="#999"
                size="16"
                @click.stop="showPointsInfo('member')"
            /></view>
            <text class="points-value">{{ pointsData.member }}</text>
          </view>
          <view class="points-item">
            <view class="points-label flex items-center"
              >潮客积分
              <uni-icons
                type="info"
                color="#999"
                size="16"
                @click.stop="showPointsInfo('trendy')"
            /></view>
            <text class="points-value">{{ pointsData.trendy }}</text>
          </view>
        </view>
      </view>

      <!-- Tab 切换和日期选择器组合 -->
      <view class="tab-date-container">
        <!-- Tab 切换 -->
        <view class="tab-list">
          <view
            v-for="(tab, index) in tabList"
            :key="index"
            class="tab-item"
            :class="{ active: currentTab === index }"
            @click="switchTab(index)"
          >
            <text>{{ tab.name }}</text>
            <view v-if="currentTab === index" class="tab-indicator"></view>
          </view>
        </view>

        <!-- 日期选择器 -->
        <view class="date-selector" @click="showDatePicker">
          <text class="date-text"
            >{{ dateRange.start }} - {{ dateRange.end }}</text
          >
          <uni-icons type="calendar" size="18" color="#ff9500"></uni-icons>
        </view>
      </view>

      <!-- 积分明细列表 -->
      <view class="points-list">
        <view
          v-for="(item, index) in pointsList"
          :key="index"
          class="points-item-card"
          @click="goToDetail(item)"
        >
          <!-- 购物获得标签 -->
          <view v-if="item.tag" class="tag-badge">{{ item.tag }}</view>

          <view class="card-content">
            <view class="left-info">
              <view class="info-row">
                <text class="label">订单编号：</text>
                <text class="value">{{ item.orderNumber }}</text>
              </view>
              <view class="info-row merchant">
                <text class="merchant-name">{{ item.merchantName }}</text>
              </view>
              <view class="info-row">
                <text class="label">订单金额：</text>
                <text class="value amount">¥ {{ item.amount }}</text>
              </view>
              <view class="info-row">
                <text class="label">变动时间：</text>
                <text class="value">{{ item.changeTime }}</text>
              </view>
            </view>

            <view class="right-points">
              <text class="points-change">{{ item.pointsChange }}</text>
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view v-if="pointsList.length === 0" class="empty-state">
          <image
            src="/static/logo.png"
            class="empty-image"
            mode="aspectFit"
          ></image>
          <text class="empty-text">暂无数据~</text>
        </view>
      </view>
    </view>

    <!-- 日期选择弹框（组件） -->
    <DateRangePicker
      ref="datePickerRef"
      v-model="dateRange"
      @confirm="onDateConfirm"
    />

    <!-- 积分说明弹框 -->
    <uni-popup ref="pointsInfoPopup" type="center">
      <view class="points-info-modal">
        <view class="modal-header">
          <text class="modal-title">{{ pointsInfo.title }}</text>
          <uni-icons
            type="close"
            size="24"
            color="#666"
            @click="closePointsInfo"
          ></uni-icons>
        </view>
        <view class="modal-content">
          <text class="content-text">{{ pointsInfo.content }}</text>
        </view>
        <view class="modal-footer">
          <view class="confirm-btn" @click="closePointsInfo">知道了</view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed } from "vue";
import DateRangePicker from "./components/DateRangePicker.vue";

// Tab 列表
const tabList = ref([
  { name: "补贴积分" },
  { name: "会员积分" },
  { name: "潮客积分" },
]);

// 当前选中的 Tab
const currentTab = ref(0);

// 积分数据
const pointsData = ref({
  subsidy: "17294.68",
  member: "4164.73",
  trendy: "154.94",
});

// 日期范围
const dateRange = ref({
  start: "2025-09-21",
  end: "2025-10-21",
});

// 临时日期范围（用于弹框）
const tempDateRange = ref({
  start: "2025-10-01",
  end: "2025-10-31",
});

// 弹框引用（组件）
const datePickerRef = ref(null);

// 积分说明弹框引用
const pointsInfoPopup = ref(null);

// 积分说明信息
const pointsInfo = ref({
  title: "",
  content: "",
});

// 积分说明数据
const pointsInfoData = {
  subsidy: {
    title: "商户积分",
    content: "商户参与平台推广活动获得的积分",
  },
  member: {
    title: "会员积分",
    content: "商户作为我店会员消费等行为获得的积分",
  },
  trendy: {
    title: "潮客积分",
    content: "商户分享潮客粉丝交易获得的积分",
  },
};

// 当前激活的输入框
const activeInput = ref("start");

// 年月日列表（滚轮）
const years = ref([]);
const months = ref([]);
const days = ref([]);

// 选中的年份
const selectedYear = ref(2025);

// 选中的月份
const selectedMonth = ref(10);

// 选中的日期
const selectedDay = ref(1);

// 积分明细列表
const pointsList = ref([
  {
    orderNumber: "197904982776267162O",
    merchantName: "浙江乡盟电子商务有限公司",
    amount: "127.00",
    changeTime: "2025-10-17 13:00:27",
    pointsChange: "+ 25.4000",
    tag: "购物获得",
  },
  {
    orderNumber: "197999454384824478",
    merchantName: "比郭多鲜果红五月店",
    amount: "88.60",
    changeTime: "2025-10-14 15:26:38",
    pointsChange: "+ 17.7200",
    tag: "购物获得",
  },
  {
    orderNumber: "197508029151022696g",
    merchantName: "浙江乡盟电子商务有限公司",
    amount: "70.00",
    changeTime: "2025-10-06 14:06:55",
    pointsChange: "+ 14.0000",
    tag: "购物获得",
  },
  {
    orderNumber: "197505222104682087I",
    merchantName: "比郭多鲜果红五月店",
    amount: "168.00",
    changeTime: "2025-10-06 12:15:22",
    pointsChange: "+ 33.6000",
    tag: "购物获得",
  },
]);

// 滚轮当前值 [yearIndex, monthIndex, dayIndex]
const pickerValue = ref([0, 0, 0]);

// 选中指示器样式，与 item 高度一致
const indicatorStyle = "height: 68rpx;";

// 初始化年月日与滚轮默认值
const initPicker = () => {
  const now = new Date();
  const currentYear = now.getFullYear();
  const currentMonth = now.getMonth() + 1; // 1-12
  const currentDay = now.getDate();

  // 年份：当前-5年至当前+1年
  years.value = [];
  for (let y = currentYear - 5; y <= currentYear + 1; y++) years.value.push(y);

  // 月份：01-12
  months.value = Array.from({ length: 12 }, (_, i) =>
    String(i + 1).padStart(2, "0")
  );

  // 天数：根据当前年月生成
  const numDays = new Date(currentYear, currentMonth, 0).getDate();
  days.value = Array.from({ length: numDays }, (_, i) =>
    String(i + 1).padStart(2, "0")
  );

  const yearIdx = years.value.findIndex((y) => y === currentYear);
  const monthIdx = currentMonth - 1;
  const dayIdx = Math.min(currentDay - 1, days.value.length - 1);
  pickerValue.value = [yearIdx, monthIdx, dayIdx];
};

// 初始化年份列表
const initYears = () => {
  const currentYear = new Date().getFullYear();
  for (let i = currentYear - 5; i <= currentYear + 1; i++) {
    years.value.push(i);
  }
};

initYears();
initPicker();

// 返回
const goBack = () => {
  uni.navigateBack();
};

// 显示积分说明
const showPointsInfo = (type) => {
  const info = pointsInfoData[type];
  if (info) {
    pointsInfo.value = { ...info };
    pointsInfoPopup.value?.open();
  }
};

// 关闭积分说明
const closePointsInfo = () => {
  pointsInfoPopup.value?.close();
};

// 切换 Tab
const switchTab = (index) => {
  currentTab.value = index;
  // TODO: 根据不同 Tab 加载不同数据
};

// 显示日期选择器
const showDatePicker = () => {
  datePickerRef.value?.open();
};

// 组件回调：确认
const onDateConfirm = (val) => {
  dateRange.value = { ...val };
};

// 跳转到详情页面
const goToDetail = (item) => {
  console.log("查看详情:", item);
  // TODO: 可以通过 URL 参数传递订单信息
  uni.navigateTo({
    url: `/pages/index/pointsDetail/memberRewardDetail?orderNumber=${item.orderNumber}`,
  });
};

// 选择年份
const selectYear = (year) => {
  selectedYear.value = year;
};

// 选择月份
const selectMonth = (month) => {
  selectedMonth.value = month;
  // 重置日期选择
  selectedDay.value = 1;
};

// 滚轮变化
const pickerChange = (e) => {
  const [yIdx, mIdx, dIdx] = e.detail.value;
  const year = years.value[yIdx];
  const month = Number(months.value[mIdx]);

  // 当年或月变化时，重建天数，保持天索引不越界
  const newNumDays = new Date(year, month, 0).getDate();
  days.value = Array.from({ length: newNumDays }, (_, i) =>
    String(i + 1).padStart(2, "0")
  );
  const safeDayIdx = Math.min(dIdx, days.value.length - 1);
  pickerValue.value = [yIdx, mIdx, safeDayIdx];

  // 同步实时选择到当前激活的输入框
  const picked = `${year}-${String(month).padStart(2, "0")}-${
    days.value[safeDayIdx]
  }`;
  if (activeInput.value === "start") {
    tempDateRange.value.start = picked;
    // 若开始时间超过当前结束时间，则自动把结束时间同步为开始时间
    if (dateToTs(picked) > dateToTs(tempDateRange.value.end)) {
      tempDateRange.value.end = picked;
    }
  } else {
    // 结束时间不得小于开始时间
    if (dateToTs(picked) < dateToTs(tempDateRange.value.start)) {
      uni.showToast({ title: "结束时间不能小于开始时间", icon: "none" });
      tempDateRange.value.end = tempDateRange.value.start;
      setPickerByDate(tempDateRange.value.end);
      return;
    }
    tempDateRange.value.end = picked;
  }
};

// 将滚轮同步到指定日期 yyyy-mm-dd
const setPickerByDate = (dateStr) => {
  if (!dateStr) return;
  const [yStr, mStr, dStr] = dateStr.split("-");
  const year = Number(yStr);
  const month = Number(mStr);
  const day = Number(dStr);

  // 重建该年月对应的天数
  const numDays = new Date(year, month, 0).getDate();
  days.value = Array.from({ length: numDays }, (_, i) =>
    String(i + 1).padStart(2, "0")
  );

  const yIdx = years.value.findIndex((y) => y === year);
  const mIdx = months.value.findIndex(
    (m) => m === String(month).padStart(2, "0")
  );
  const dIdx = Math.min(
    days.value.findIndex((d) => d === String(day).padStart(2, "0")),
    days.value.length - 1
  );

  // 兜底：若年份不在范围内则不更新
  if (yIdx !== -1 && mIdx !== -1 && dIdx !== -1) {
    pickerValue.value = [yIdx, mIdx, dIdx];
  }
};

// 从滚轮获取 yyyy-mm-dd 字符串
const getDateFromPicker = () => {
  const [yIdx, mIdx, dIdx] = pickerValue.value;
  const y = years.value[yIdx];
  const m = months.value[mIdx];
  const d = days.value[dIdx];
  return `${y}-${m}-${d}`;
};

// 日期转时间戳（避免不同环境解析差异）
const dateToTs = (str) => {
  const [y, m, d] = str.split("-").map((n) => Number(n));
  return new Date(y, m - 1, d).getTime();
};

// 重置日期
const resetDate = () => {
  const now = new Date();
  const endDate = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(
    2,
    "0"
  )}-${String(now.getDate()).padStart(2, "0")}`;

  const startDate = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
  const startDateStr = `${startDate.getFullYear()}-${String(
    startDate.getMonth() + 1
  ).padStart(2, "0")}-${String(startDate.getDate()).padStart(2, "0")}`;

  tempDateRange.value = {
    start: startDateStr,
    end: endDate,
  };
};

// 确认日期（根据当前激活输入框写入）
const confirmDate = () => {
  const picked = getDateFromPicker();
  if (activeInput.value === "start") {
    tempDateRange.value.start = picked;
  } else {
    tempDateRange.value.end = picked;
  }
  dateRange.value = { ...tempDateRange.value };
  datePopup.value?.close();
  // TODO: 根据日期范围重新加载数据
};
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.content {
  padding: 16rpx;
  padding-top: 20rpx;
}

// 顶部积分卡片
.points-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
}

.points-row {
  display: flex;
  justify-content: space-around;
  gap: 32rpx;
}

.points-item {
  flex: 1;
  text-align: center;

  &:active {
    opacity: 0.7;
  }
}

.points-label {
  font-size: 24rpx;
  color: #999;
  justify-content: center;
  margin-bottom: 16rpx;
}

.points-value {
  display: block;
  font-size: 32rpx;
  color: #333;
  font-weight: 600;
}

// Tab 和日期选择器组合容器
.tab-date-container {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 0 32rpx 32rpx;
  margin-bottom: 24rpx;
}

.tab-list {
  display: flex;
  align-items: center;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 32rpx 0;
  position: relative;
  font-size: 28rpx;
  color: #666;

  &.active {
    color: #333;
    font-weight: 500;
  }

  &:active {
    opacity: 0.7;
  }
}

.tab-indicator {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 6rpx;
  background-color: #ff9500;
  border-radius: 3rpx;
}

// 日期选择器
.date-selector {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #f5f5f5;
  padding: 0rpx 16rpx;
  border-radius: 50rpx;
  margin-top: 16rpx;

  &:active {
    opacity: 0.8;
  }
}

.date-text {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

// 积分列表
.points-list {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.points-item-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 16rpx;
  position: relative;
  overflow: hidden;
  cursor: pointer;

  &:active {
    background-color: #f9f9f9;
  }
}

// 右上角标签
.tag-badge {
  position: absolute;
  top: 0;
  right: 0;
  padding: 8rpx 24rpx;
  background-color: #ff9500;
  color: #fff;
  font-size: 24rpx;
  border-radius: 0 16rpx 0 16rpx;
}

.card-content {
  display: flex;
  justify-content: space-between;
  gap: 24rpx;
}

.left-info {
  flex: 1;
  padding-top: 8rpx;
}

.info-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 12rpx;

  &.merchant {
    margin-bottom: 16rpx;
  }

  &:last-child {
    margin-bottom: 0;
  }

  .label {
    font-size: 28rpx;
    color: #666;
    flex-shrink: 0;
  }

  .value {
    font-size: 28rpx;
    color: #333;
    word-break: break-all;

    &.amount {
      font-weight: 500;
    }
  }

  .merchant-name {
    font-size: 30rpx;
    color: #333;
    font-weight: 600;
  }
}

.right-points {
  display: flex;
  align-items: center;
  padding-top: 8rpx;
}

.points-change {
  font-size: 40rpx;
  color: #ff2d2d;
  font-weight: 700;
  white-space: nowrap;
}

// 空状态
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
}

.empty-image {
  width: 300rpx;
  height: 300rpx;
  margin-bottom: 32rpx;
  opacity: 0.3;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

// 积分说明弹框
.points-info-modal {
  background: #fff;
  border-radius: 16rpx;
  width: 600rpx;
  overflow: hidden;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.modal-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 600;
}

.modal-content {
  padding: 48rpx 32rpx;
  text-align: center;
}

.content-text {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
}

.modal-footer {
  padding: 0 32rpx 32rpx;
}

.confirm-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  background: #faa820;
  color: #fff;
  font-size: 32rpx;
  font-weight: 600;
  border-radius: 12rpx;

  &:active {
    opacity: 0.8;
  }
}

// 日期选择弹框
.date-picker-modal {
  background: #fff;
  border-radius: 16rpx 16rpx 0 0;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.picker-view {
  height: 400rpx;
  padding: 0 32rpx 16rpx;
}

.picker-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 68rpx;
  font-size: 32rpx;
  color: #333;
}

.picker-header {
  padding: 32rpx;
  border-bottom: 1rpx solid #f5f5f5;
  text-align: center;
}

.picker-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.date-input-row {
  padding: 24rpx 32rpx;
}

.date-label {
  font-size: 28rpx;
  color: #333;
}

.date-range-picker {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32rpx 24rpx;
  gap: 16rpx;
}

.date-input {
  flex: 1;
  padding: 20rpx;
  background-color: #f5f5f5;
  border: 2rpx solid transparent;
  border-radius: 8rpx;
  text-align: center;
  font-size: 28rpx;
  color: #333;

  &.active {
    border-color: #ff9500;
    background-color: #fff5e6;
  }
}

.date-separator {
  font-size: 28rpx;
  color: #999;
}

// 日历容器
.calendar-container {
  flex: 1;
  overflow-y: auto;
  padding: 0 32rpx;
}

.calendar-header {
  margin-bottom: 24rpx;
}

.year-list {
  display: flex;
  gap: 16rpx;
  overflow-x: auto;
  white-space: nowrap;
  padding-bottom: 16rpx;

  &::-webkit-scrollbar {
    display: none;
  }
}

.year-item {
  flex-shrink: 0;
  padding: 12rpx 24rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #666;

  &.active {
    background-color: #ff9500;
    color: #fff;
  }

  &:active {
    opacity: 0.7;
  }
}

// 月份和日期容器（左右并排）
.month-day-container {
  display: flex;
  gap: 24rpx;
  margin-bottom: 24rpx;
}

// 左侧月份列表
.month-list {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16rpx;
  max-height: 600rpx;
  overflow-y: auto;
}

.month-item {
  padding: 20rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  text-align: center;
  font-size: 28rpx;
  color: #333;

  &.active {
    background-color: #ff9500;
    color: #fff;
  }

  &:active {
    opacity: 0.7;
  }
}

// 右侧日期列表
.day-list {
  flex: 2;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16rpx;
  max-height: 600rpx;
  overflow-y: auto;
  align-content: start;
}

.day-item {
  padding: 16rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  text-align: center;
  font-size: 28rpx;
  color: #333;

  &.active {
    background-color: #ff9500;
    color: #fff;
  }

  &:active {
    opacity: 0.7;
  }
}

.picker-footer {
  display: flex;
  gap: 24rpx;
  padding: 24rpx 32rpx;
  border-top: 1rpx solid #f5f5f5;
}

.footer-btn {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  font-size: 32rpx;
  border-radius: 12rpx;

  &:active {
    opacity: 0.8;
  }
}

.reset-btn {
  background-color: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background: #faa820;
  color: #fff;
  font-weight: 600;
}
</style>
